
using AutoMapper;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
using Org.BouncyCastle.Utilities.Collections;
using RestSharp;
using SqlSugar;
using System.Reflection;
using Util;

namespace API.Controllers
{
    public class MaintenanceApplyController : BaseController
    {
        Repository<tMaintenanceApply> _MaintenanceApply;
        Repository<tConfiguration> _tConfig;
        Repository<tStaff> _Staff;
        Repository<tUserComputer> _Computer;
        Repository<tMaintenance> _Maintenance;
        readonly IMapper _mapper;
        ISqlSugarClient _db;
        public MaintenanceApplyController(Repository<tMaintenanceApply> MaintenanceApply, IMapper mapper, Repository<tConfiguration> tConfig, Repository<tStaff> staff, Repository<tUserComputer> computer, ISqlSugarClient db, Repository<tMaintenance> Maintenance)
        {
            _MaintenanceApply = MaintenanceApply;
            _mapper = mapper;
            _tConfig = tConfig;
            _Staff = staff;
            _Computer = computer;
            _db = db;
            _Maintenance = Maintenance;
        }
        /// <summary>
        /// 设置维修负责人
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> setMaintenanceLeader([FromBody] setMaintenanceLeaderInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                if (dto.UserIds == null || dto.UserIds.Count() == 0)
                {
                    return result.Error("请选择维修负责人!");
                }
                var model = await _tConfig.GetFirstAsync(a => a.FCode == "MaintenanceLeader");
                if (model == null)
                {
                    model = new tConfiguration();
                    model.FCode = "MaintenanceLeader";
                    model.FDescribe = "维修负责人";
                    model.FCodeValue = string.Join(",", dto.UserIds);
                    InitEntity(model);
                    await _tConfig.InsertAsync(model);
                }
                else
                {
                    model.FCodeValue = string.Join(",", dto.UserIds);
                    model.CreateTime = DateTime.Now;
                    await _tConfig.UpdateAsync(model);
                }
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MaintenanceApplyController--setMaintenanceLeader:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 获取维修负责人列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<StaffOutput>>> GetMaintenanceLeaderList()
        {
            ResultMsg<List<StaffOutput>> result = new ResultMsg<List<StaffOutput>>();
            try
            {
                List<StaffOutput> list = new List<StaffOutput>();
                var model = await _tConfig.GetFirstAsync(a => a.FCode == "MaintenanceLeader");
                if (model == null)
                {

                }
                List<string> ids = model.FCodeValue.Split(",").ToList();
                var exp = Expressionable.Create<tStaff>();
                exp.And(x => !x.FDeleted && ids.Contains(x.FUserId));
                list = (await _Staff.GetListAsync(exp.ToExpression())).OrderBy(c => c.FUserName).Select(a => new StaffOutput
                {
                    UserId = a.FUserId,
                    UserName = a.FUserName,
                }).ToList();
                return result.Success(list);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("UserComputerController--GetMaintenanceLeaderList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 小程序申请维修
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> SaveMini([FromBody] SaveMiniInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var old = (await _MaintenanceApply.GetListAsync(c => c.FUserID == CurrentUserId)).OrderByDescending(t => t.CreateTime).FirstOrDefault();
                if (old != null)
                {
                    if (DateTime.Now.Subtract(old.CreateTime) < TimeSpan.FromHours(1))
                    {
                        return result.Error("1小时内你已提交了一次,请静候处理");
                    }
                }
                tMaintenanceApply model = new tMaintenanceApply();
                string computerId = dto.ComputerId;
                if (string.IsNullOrEmpty(computerId))
                {
                    computerId = (await _Computer.GetFirstAsync(t => t.FUserID == CurrentUserId)).FComputerId;
                }
                model.FUserID = CurrentUserId;
                model.FComputerId = computerId;
                model.FQuestionType = dto.QuestionType;
                model.FRemark = dto.Remark;
                var config = await _tConfig.GetFirstAsync(c => c.FCode == "MaintenanceLeader");
                model.FLeader = config.FCodeValue;
                model.FAssign = "";
                model.FStatus = 0;
                model.FDeleted = false;
                InitEntity(model);
                await _MaintenanceApply.InsertAsync(model);

                var ids = config.FCodeValue.Split(",").ToList();
                foreach (var item in ids)
                {
                    var client = new RestClient("https://app.yingdl.com:9527/Wechat/SendMsgToOne");
                    var request = new RestRequest("", RestSharp.Method.Get);
                    request.AddParameter("userid", item);
                    request.AddParameter("userName", "");
                    request.AddParameter("content", $"你有一个新的维修申请,请及时处理!{GetQuestion(model.FQuestionType)}");
                    request.AddParameter("first", "");
                    request.AddParameter("remark", "");
                    request.AddParameter("path", "");
                    var response = client.Execute(request);
                }
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MaintenanceApplyController--SaveMini:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> Save([FromBody] SaveMaintenanceApplyInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = _mapper.Map<tMaintenanceApply>(dto);
                InitEntity(model);
                await _MaintenanceApply.InsertOrUpdateAsync(model);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MaintenanceApplyController--Save:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        private string GetQuestion(int questionType)
        {
            string str = "";
            switch (questionType)
            {
                case 1:
                    str = "显示器无显示";
                    break;
                case 2:
                    str = "电脑无法上网";
                    break;
                case 3:
                    str = "CRM无法打开";
                    break;
                default:
                    break;
            }
            return str;
        }
        /// <summary>
        /// 指派维修人员
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> SaveAssign([FromBody] SaveAssignInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = await _MaintenanceApply.GetFirstAsync(c => c.Id == dto.Id);
                if (model == null)
                {
                    return result.Error("数据不存在");
                }
                model.FAssign = String.Join(",", dto.UserIds);
                model.FStatus = 1;
                await _MaintenanceApply.UpdateAsync(model);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MaintenanceApplyController--SaveAssign:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<MaintenanceApplyOutput>>> GetList([FromBody] MaintenanceApplyListInput dto)
        {
            ResultMsg<List<MaintenanceApplyOutput>> result = new ResultMsg<List<MaintenanceApplyOutput>>();
            try
            {
                if (dto.PageNum <= 0)
                {
                    return result.Error("PageNum不能小于或等于0");
                }
                if (dto.PageSize <= 0)
                {
                    return result.Error("PageSize不能小于或等于0");
                }
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel
                {
                    PageIndex = dto.PageNum,
                    PageSize = dto.PageSize,
                };
                var staffList = await _Staff.GetListAsync();
                var exp = Expressionable.Create<tMaintenanceApply, tStaff, tUserComputer,tStaff>();
                exp.And((a,b,c,d)=>!a.FDeleted);
                if (!string.IsNullOrWhiteSpace(dto.UserName))
                {
                    exp.And((a, b, c, d) => b.FUserName.Contains(dto.UserName));
                }
                if (!string.IsNullOrEmpty(dto.ComputerId))
                {
                    exp.And((a, b, c, d) => a.FComputerId.Contains(dto.ComputerId));
                }
                if (!string.IsNullOrEmpty(dto.ComputerName))
                {
                    exp.And((a, b, c, d) => c.FSysHostName.Contains(dto.ComputerName));
                }
                if (dto.Status != null && (int)dto.Status != -1)
                {
                    exp.And((a, b, c, d) => a.FStatus == dto.Status);
                }
                if (!string.IsNullOrEmpty(dto.AssignName))
                {
                    exp.And((a, b, c, d) => d.FUserName.Contains(dto.AssignName));
                }
                var list = await _db.Queryable<tMaintenanceApply, tStaff, tUserComputer,tStaff  >((a, b, c,d) => new JoinQueryInfos(
                JoinType.Left, a.FUserID == b.FUserId,
                JoinType.Left, a.FComputerId == c.FComputerId,
                JoinType.Left, a.FAssign == d.FUserId
               )).Where(exp.ToExpression()).OrderByDescending((a, b, c, d) => a.CreateTime).Select((a, b, c,d) => new MaintenanceApplyOutput
               {
                   Id = a.Id,
                   UserID = a.FUserID,
                   UserName = b.FUserName,
                   ComputerId = a.FComputerId,
                   QuestionType = a.FQuestionType,
                   Remark = a.FRemark,
                   Status = a.FStatus,
                   Assign = a.FAssign,
                   Leader = a.FLeader,
                   ComputerName = c.FSysHostName,
                   AssignName=d.FUserName,
                   CreateTime=a.CreateTime
                   
               }).ToListAsync();
                foreach (var item in list)
                {
                    item.StatusStr = getStatus(item.Status);
                    item.Question = GetQuestion(item.QuestionType);
                    var main= await _Maintenance.GetFirstAsync(t => t.FMId == item.Id);
                    if(main != null)
                    {
                        item.MId = main.Id;
                        item.MRemark=main.FRemark;
                        item.Handle=main.FHandle;
                    }
                    //if (!string.IsNullOrEmpty(item.Assign))
                    //{
                    //    item.AssignName = staffList.Where(x => x.FUserId == item.Assign).FirstOrDefault()?.FUserName;
                    //}
                    if (!string.IsNullOrEmpty(item.Leader))
                    {
                        item.LeaderName = staffList.Where(x => x.FUserId == item.Leader).FirstOrDefault()?.FUserName;
                    }
                }
                return result.Success(list.Skip((pageModel.PageIndex - 1) * pageModel.PageSize).Take(pageModel.PageSize).ToList(), list.Count);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MaintenanceApplyController--GetList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
            string getStatus(int status)
            {
                string str = string.Empty;
                switch (status)
                {
                    case 0:
                        str = "已申请";
                        break;
                    case 1:
                        str = "已指派";
                        break;
                    case 2:
                        str = "维修中";
                        break;
                    case 3:
                        str = "已处理";
                        break;
                }
                return str;
            }
        }
        /// <summary>
        /// 获取唯一
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<MaintenanceApplyOutput>> GetTheOne(string id)
        {
            ResultMsg<MaintenanceApplyOutput> result = new ResultMsg<MaintenanceApplyOutput>();
            try
            {
                var model = await _MaintenanceApply.GetByIdAsync(id);
                var dao = _mapper.Map<MaintenanceApplyOutput>(model);
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MaintenanceApplyController--GetTheOne:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<string>> Del(string id)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model= await _MaintenanceApply.GetByIdAsync(id);
                model.FDeleted = true;
                await _MaintenanceApply.UpdateAsync(model);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("MaintenanceApplyController--Del:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
    }
}
